﻿using Face8280WebSocketServer.DB;
using Face8280WebSocketServer.DB.Access;
using Face8280WebSocketServer.DTO.FacePeople;
using Face8280WebSocketServer.Interface;
using Face8280WebSocketServer.Utility.FilterAttribute;
using Face8280WebSocketServer.Utility.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Face8280WebSocketServer.Controllers.FaceDevice.Remote
{
    [Route("api/[controller]")]
    [ApiController]
    public class DeviceAccessController : Controller
    {

        private readonly ILogger<DeviceAccessController> _logger;

        private IDeviceAccessService _AccessDB;
        private IFacePeopleService _FacePeopleService;
        private ICacheService _CacheService;
        public DeviceAccessController(ILogger<DeviceAccessController> logger,
            IDeviceAccessService door, IFacePeopleService facePeopleService, ICacheService cacheService)
        {
            _logger = logger;
            _AccessDB = door;
            _FacePeopleService = facePeopleService;
            _CacheService = cacheService;
        }

        [HttpPost]
        [Route("Add")]
        [Authorize]
        [TypeFilter(typeof(VerifyActionFilterAttribute))]
        public async Task<IActionResult> Add([FromForm] DeviceAccessAddParameter par)
        {

            if (par.DeviceIDs == null)
            {
                return new JsonResult(new JsonResultModel(1, "未选择需要操作的设备"));
            }
            if (par.DeviceIDs.Count == 0)
            {
                return new JsonResult(new JsonResultModel(1, "未选择需要操作的设备"));
            }

            if (par.PeopleIDs == null)
            {
                return new JsonResult(new JsonResultModel(2, "未选择需要操作的人员"));
            }
            if (par.PeopleIDs.Count == 0)
            {
                return new JsonResult(new JsonResultModel(2, "未选择需要操作的人员"));
            }

            FacePeopleAccessDetail accessDetail = new FacePeopleAccessDetail()
            {
                EmployeeRoot = par.EmployeeRoot,
                TimeGroupID = par.TimeGroupID,
                DevicePassStart = par.DevicePassStart,
                DevicePassEnd = par.DevicePassEnd,
                DevicePassTimeOver = par.DevicePassTimeOver,
                DevicePassNumber = par.DevicePassNumber
            };

            await _AccessDB.Add(par.DeviceIDs, par.PeopleIDs, par.AccessType, accessDetail);
            return new JsonResult(new JsonResultModel());
        }

        [HttpPost]
        [Route("Add_AllPeople")]
        [Authorize]
        [TypeFilter(typeof(VerifyActionFilterAttribute))]
        public async Task<IActionResult> Add_AllPeople([FromForm] DeviceAccessAddAllPeopleParameter par)
        {

            if (par.DeviceIDs == null)
            {
                return new JsonResult(new JsonResultModel(1, "未选择需要操作的设备"));
            }
            if (par.DeviceIDs.Count == 0)
            {
                return new JsonResult(new JsonResultModel(1, "未选择需要操作的设备"));
            }

            FacePeopleAccessDetail accessDetail = new FacePeopleAccessDetail()
            {
                EmployeeRoot = par.EmployeeRoot,
                TimeGroupID = par.TimeGroupID,
                DevicePassStart = par.DevicePassStart,
                DevicePassEnd = par.DevicePassEnd,
                DevicePassTimeOver = par.DevicePassTimeOver,
                DevicePassNumber = par.DevicePassNumber
            };

            await _AccessDB.Add_ALL(par.DeviceIDs, par.AccessType, accessDetail);
            return new JsonResult(new JsonResultModel());
        }


        [HttpPost]
        [Route("Delete")]
        [Authorize]
        [TypeFilter(typeof(VerifyActionFilterAttribute))]
        public IActionResult Delete([FromForm] DeviceAccessDeleteParameter par)
        {

            if (par.AccessIDs == null)
            {
                return new JsonResult(new JsonResultModel(2, "未选择需要删除的权限"));
            }
            if (par.AccessIDs.Count == 0)
            {
                return new JsonResult(new JsonResultModel(2, "未选择需要删除的权限"));
            }

            _AccessDB.Delete(par.AccessIDs);
            return new JsonResult(new JsonResultModel());
        }



        /// <summary>
        /// 获取人员权限表
        /// </summary>
        /// <param name="par"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetList")]
        [Authorize]
        [TypeFilter(typeof(VerifyActionFilterAttribute))]
        public IActionResult GetList([FromForm] DeviceAccessQueryParameter par)
        {
            //_logger.LogInformation("获取人员权限列表");
            DeviceAccessDetail_DTO queryPar = new DeviceAccessDetail_DTO()
            {
                DeviceID = par.DeviceID,
                DeviceName = par.DeviceName,
                EmployeeID = par.EmployeeID,
                EmployeeName = par.EmployeeName,
                //EmployeeJob = par.EmployeeJob,
                EmployeeIC = par.EmployeeIC,
                //EmployeePhone=par.EmployeePhone,
                EmployeeRoot = par.EmployeeRoot,
                UploadStatus = par.UploadStatus,
                UploadResult = par.UploadResult


            };
            var devices = _AccessDB.GetList(queryPar, par);

            return new JsonResult(new JsonResultModel(devices));
        }


        /// <summary>
        /// 清空所有开门权限
        /// </summary>
        /// <param name="par"></param>
        /// <returns></returns>
        [HttpDelete]
        [Route("ClearAccess")]
        [Authorize]
        public IActionResult ClearAccess()
        {
            //_logger.LogInformation("清空所有开门权限");
            _AccessDB.ClearAccess();

            return new JsonResult(new JsonResultModel());
        }


        /// <summary>
        /// 根据权限ID获取权限详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetAccessDetail")]
        [Authorize]
        public IActionResult GetAccessDetail([FromForm] int AccessID)
        {
            var detail = _AccessDB.GetAccessDetail(AccessID);
            return new JsonResult(new JsonResultModel(detail));
        }


        /// <summary>
        /// 更新单个开门权限
        /// </summary>
        [HttpPost]
        [Route("Update")]
        [Authorize]
        [TypeFilter(typeof(VerifyActionFilterAttribute))]
        public async Task<IActionResult> Update([FromForm] DeviceAccessUpdateParameter par)
        {
            FacePeopleAccessDetail updatedetail = new FacePeopleAccessDetail()
            {
                AccessID = par.AccessID,
                EmployeeRoot = par.EmployeeRoot,
                TimeGroupID = par.TimeGroupID,
                DevicePassStart = par.DevicePassStart,
                DevicePassEnd = par.DevicePassEnd,
                DevicePassTimeOver = par.DevicePassTimeOver,
                DevicePassNumber = par.DevicePassNumber

            };
            await _AccessDB.Update(updatedetail);
            return new JsonResult(new JsonResultModel());
        }


        /// <summary>
        /// 使指定的权限重新上传
        /// </summary>
        [HttpPost]
        [Route("Reupload")]
        [Authorize]
        public IActionResult Reupload([FromForm] List<int> accessIDs)
        {
            if (accessIDs == null)
            {
                return new JsonResult(new JsonResultModel(2, "未选择需要重新上传的权限"));
            }
            if (accessIDs.Count == 0)
            {
                return new JsonResult(new JsonResultModel(2, "未选择需要重新上传的权限"));
            }
            _AccessDB.Reupload(accessIDs);
            return new JsonResult(new JsonResultModel());
        }


        /// <summary>
        /// 使全部的权限重新上传
        /// </summary>
        [HttpPost]
        [Route("ReuploadAll")]
        [Authorize]
        public IActionResult ReuploadAll()
        {
            _AccessDB.ReuploadAll();
            return new JsonResult(new JsonResultModel());
        }
        [HttpPost]
        [Route("AddPeopleAndAccess")]
        [Authorize]
        public async Task<IActionResult> AddPeopleAndAccess([FromForm] AddPeoplAndAccessParameter parameter)
        {
            var device = _CacheService.GetDevice(parameter.DeviceID);
            if (device == null)
            {
                return Json(new JsonResultModel(101, $"没有找到SN={parameter.DeviceID}的设备"));
            }
            byte[] photoData = null;
            if (!string.IsNullOrWhiteSpace(parameter.EmployeePhoto))
            {
                var name = "base64,";
                if (parameter.EmployeePhoto.Contains(name))
                {
                    var index = parameter.EmployeePhoto.IndexOf(name);
                    parameter.EmployeePhoto = parameter.EmployeePhoto.Substring(index + name.Length);
                }
                photoData = Convert.FromBase64String(parameter.EmployeePhoto);
            }
            var result = _FacePeopleService.Add(new DB.People.FacePeopleInfo
            {
                Name = parameter.EmployeeName,
                Card = parameter.EmployeeIC,
                Pin = parameter.EmployeePassword,
                Admin = (byte)parameter.EmployeeRoot,
                Code = (uint)parameter.EmployeeID,
                Job = parameter.EmployeeJob,
                Phone = parameter.EmployeePhone,
                PhotoData = photoData
            });
            if (result.result == false)
            {
                return Json(result);
            }
            var people = _FacePeopleService.GetPeopleByCode((uint)parameter.EmployeeID);
            FacePeopleAccessDetail accessDetail = new FacePeopleAccessDetail()
            {
                DeviceID = device.Id,
                PeopleID = people.Id,
                EmployeeRoot = parameter.EmployeeRoot,
                TimeGroupID = parameter.TimeGroupID,
                DevicePassStart = parameter.DevicePassStart,
                DevicePassEnd = parameter.DevicePassEnd,
                DevicePassTimeOver = parameter.DevicePassTimeOver,
                DevicePassNumber = parameter.DevicePassNumber
            };
            await _AccessDB.Add(new List<int> { device.Id }, new List<int> { people.Id }, 1, accessDetail);
            return Json(new JsonResultModel());
        }

    }
}
